/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.servlet.niceshot;

import br.com.aluguel.niceshot.AluguelQueries;
import br.com.niceshot.PresetQueries;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "AgendaDiaServlet", urlPatterns = {"/AgendaDiaServlet"})
public class AgendaDiaServlet extends HttpServlet {

    AluguelQueries pQueries = new AluguelQueries();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");

        processRequest(request, response);

        try (PrintWriter out = response.getWriter()) {
            // Verifica se a requisição possui ID e Ação = Edição
            // Caso exista um ID é considerado modo de Edição, por exemplo.
            //caso contrário interpreta-se como uma Busca de Usuário
            String idAluguel = request.getParameter("id");
            String acao = request.getParameter("acao");
            if (idAluguel != null) {
                if (acao.equals("editar")) {
                    out.println(editAluguel(idAluguel));
                } else {
                    out.println(removeAluguel("aluguel", "id_aluguel", idAluguel));
                }
            } else {
                String nmSocio = request.getParameter("nmSocio");
                out.println(buscaSocio(nmSocio));
            }

        }
    }

    private String buscaSocio(String nmSocio) {
        return "{" + pQueries.HashMapToJson("BuscaSocio", pQueries.SelectLikePessoa(nmSocio, "socio")) + "}";
    }

    private String removeAluguel(String tabela, String nmCampoId, String idAluguel) {
        String resposta = pQueries.RemoveData(tabela, nmCampoId, idAluguel);
        return resposta;
    }

    private String insereAluguelEquipamento(String[] idEquipamento, String[] qtMunicao, String idAluguel) {
        removeAluguel("aluguel_equipamento", "id_aluguel", idAluguel);

        if (qtMunicao != null) {
            LinkedHashMap<String, String> dataAluguelEquipamento = new LinkedHashMap<String, String>();

            for (int i = 0; i < idEquipamento.length; i++) {
                dataAluguelEquipamento.put("id_equipamento", idEquipamento[i]);
                dataAluguelEquipamento.put("qt_equipamento", qtMunicao[i]);
                dataAluguelEquipamento.put("id_aluguel", idAluguel);
                pQueries.InsertData("aluguel_equipamento", dataAluguelEquipamento);
            }

            return "Success";
        }
        return "Success";

    }

    private String editAluguel(String idAluguel) {
        Map<String, String> registros = new HashMap<String, String>();

        registros = pQueries.SelectByID(idAluguel, "Aluguel");

        ArrayList<Object> objAluguelEquipamento = pQueries.SelectQuery("SELECT a.id_equipamento, a.qt_equipamento, e.nm_equipamento, e.vl_municao FROM aluguel_equipamento AS a"
                + " INNER JOIN equipamento AS e ON a.id_equipamento = e.id_equipamento"
                + " WHERE "
                + " a.id_aluguel = " + idAluguel);

        String JsonAluguelEquipamentos = pQueries.ArrayObjectHashMapToJson("AluguelEquipamentos", objAluguelEquipamento);

        String JsonRegistros = pQueries.HashMapToJson("Aluguel", registros);
        String JsonNmSocio = pQueries.HashMapToJson("Socio", pQueries.SelectOnlyField("socio AS s INNER JOIN pessoa AS p ON s.id_pessoa = p.id_pessoa", "nm_pessoa", registros.get("id_socio")));
        ArrayList<Object> objEquipamento = pQueries.SelectAll("equipamento");
        ArrayList<Object> objBaia = pQueries.SelectAll("baia");
        String JsonNmBaia = pQueries.ArrayObjectHashMapToJson("Baia", objBaia);
        String JsonNmEquipamento = pQueries.ArrayObjectHashMapToJson("Equipamento", objEquipamento);

        String dataJson = "{" + JsonRegistros + "," + JsonNmSocio + "," + JsonAluguelEquipamentos + "," + JsonNmEquipamento + "," + JsonNmBaia + "}";

        return dataJson;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

        try (PrintWriter out = response.getWriter()) {

            String idAluguel = request.getParameter("id_aluguel");
            String hrEntrada = request.getParameter("hr_entrada");
            String hrSaida = request.getParameter("hr_saida");
            String vlAluguel = request.getParameter("vl_aluguel");
            String idBaia = request.getParameter("id_baia");
            String idSocio = request.getParameter("id_socio");
            String dtAluguel = request.getParameter("dt_aluguel");

            Date dateDtAluguel = new SimpleDateFormat("dd/MM/yyyy").parse(dtAluguel);
            dtAluguel = new SimpleDateFormat("yyyy-MM-dd").format(dateDtAluguel);

            LinkedHashMap<String, String> dataAluguel = new LinkedHashMap<String, String>();
            if (idAluguel.length() < 1) {
                dataAluguel.put("id_aluguel", null);
            } else {
                dataAluguel.put("id_aluguel", idAluguel);
            }

            dataAluguel.put("dt_aluguel", "'" + dtAluguel + "'");
            dataAluguel.put("hr_entrada", "'" + hrEntrada + "'");
            dataAluguel.put("hr_saida", "'" + hrSaida + "'");
            dataAluguel.put("vl_aluguel", vlAluguel);
            dataAluguel.put("id_baia", idBaia);
            dataAluguel.put("id_socio", idSocio);

            if (idAluguel.length() < 1) {
                idAluguel = pQueries.insertAluguel(dataAluguel);
            } else {
                pQueries.UpdateData("aluguel", dataAluguel);

            }

            String[] idEquipamento = request.getParameterValues("id_equipamento");
            String[] qtMunicao = request.getParameterValues("qt_municao");
            out.println(insereAluguelEquipamento(idEquipamento, qtMunicao, idAluguel));

        } catch (ParseException ex) {
            Logger.getLogger(AgendaDiaServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "AgendaDiaServlet - AluguelServlet";
    }// </editor-fold>

}
